<template>
  <view class="order-list-page">
    <!-- 顶部标签页 -->
    <wd-tabs v-model="activeTab" sticky>
      <wd-tab v-for="tab in tabs" :key="tab.type" :title="tab.name">
        <view class="tab-content">
          <!-- 订单列表 -->
          <block v-if="orderList.length > 0">
            <view class="order-item" v-for="order in orderList" :key="order.id">
              <view class="order-header">
                <view class="store-info">
                  <wd-icon name="store" />
                  <text class="store-name">智享家家电</text>
                </view>
                <text class="order-status">{{ order.statusText }}</text>
              </view>

              <view class="goods-list">
                <view class="goods-item" v-for="goods in order.goodsList" :key="goods.id">
                  <image :src="goods.image" mode="aspectFill" class="goods-image" />
                  <view class="goods-info">
                    <view class="goods-name">{{ goods.name }}</view>
                    <view class="goods-price">
                      <text class="price">¥{{ goods.price }}</text>
                      <text class="quantity">
                        <text class="multiply">×</text>
                        <text class="num">{{ goods.num }}</text>
                      </text>
                    </view>
                  </view>
                </view>
              </view>

              <view class="order-footer">
                <view class="total">
                  实付款<text class="amount">{{ order.totalAmount }}</text>
                </view>
                <view class="btn-group">
                  <!-- 查看详情按钮始终显示 -->
                  <wd-button size="small" type="info" @click="handleOrderAction('detail', order)">查看详情</wd-button>
                  <!-- 根据不同状态显示不同按钮 -->
                  <template v-if="order.status == '0'">
                    <wd-button size="small" type="warning"
                      @click="handleOrderAction('cancel', order)">取消订单</wd-button>
                    <wd-button size="small" type="primary" @click="handleOrderAction('pay', order)">立即付款</wd-button>
                  </template>
                  <template v-if="order.status == '1'">
                    <wd-button size="small" type="primary" @click="handleApplyRefund(order.id)">申请退款</wd-button>
                  </template>
                  <template v-if="order.status == '2'">
                    <wd-button size="small" type="primary" @click="handleApplyRefund(order.id)">申请退款</wd-button>
                  </template>
                  <template v-if="order.status == '3'">
                    <wd-button size="small" type="primary" @click="handleConfirmReceive(order.id)">确认收货</wd-button>
                  </template>
                  <template v-if="order.status == '4'">
                    <wd-button size="small" type="primary" @click="handleApplyRefund(order.id)">申请退款</wd-button>
                    <wd-button size="small" type="primary" @click="confirmPickup(order.id)">确认自提</wd-button>
                  </template>
                  <template v-if="order.status == '5' && order.canComment == 1">
                    <wd-button size="small" type="primary" @click="handleOrderAction('rate', order)">评价</wd-button>
                  </template>
                  <template v-if="order.status == '6'">
                    <wd-button size="small" type="primary" @click="handleOrderAction('refundDetail', order)">退款详情</wd-button>
                  </template>
                  <template v-if="order.status == '9'">
                    <wd-button size="small" type="primary" @click="handleOrderAction('refundDetail', order)">退款详情</wd-button>
                  </template>
                </view>
              </view>
            </view>
            <!-- 加载更多提示 -->
            <view class="load-more" v-if="hasMore">
              <wd-loading type="spinner" color="#ff6010" />
              <text>加载中...</text>
            </view>
            <view class="load-more" v-else>
              <text>没有更多订单了</text>
            </view>
          </block>

          <!-- 空状态 -->
          <view v-else class="empty-state">
            <image src="/static/images/empty-order.png" mode="aspectFit" />
            <text>暂无相关订单</text>
          </view>
        </view>
      </wd-tab>
    </wd-tabs>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue'
import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { getOrderList, completeOrder, applyRefund } from '@/api/order'


// 修改标签页配置，与接口状态对应
const tabs = [
  { name: '全部', type: '0' },
  { name: '待付款', type: '1' },
  { name: '待发货', type: '2' },
  { name: '待收货', type: '3' },
  { name: '待自提', type: '4' },
  { name: '待评价', type: '5' },
  { name: '退款/售后', type: '6' }
]

const activeTab = ref(0)
const orderList = ref([])
const pageSize = 10
const currentPage = ref(1)
const hasMore = ref(true)

// 获取订单列表
const loadOrders = async (type = '0', isRefresh = false) => {
  try {
    if (isRefresh) {
      // 下拉刷新，重置页码
      currentPage.value = 1
      orderList.value = []
    }

    uni.showLoading({ title: '加载中...' })

    const params = {
      current: currentPage.value,
      size: pageSize,
      status: type
    }

    const res = await getOrderList(params)

    // 处理订单数据
    const newOrders = res.records.map(order => ({
      id: order.id,
      status: order.status.toString(),
      statusText: getStatusText(order.status),
      totalAmount: order.realAmount.toFixed(2),
      canComment: order.canComment,
      goodsList: order.items.map(item => ({
        id: item.id,
        image: item.productImage,
        name: item.productName,
        price: item.price,
        num: item.quantity
      }))
    }))

    if (isRefresh) {
      orderList.value = newOrders
    } else {
      orderList.value = [...orderList.value, ...newOrders]
    }

    // 判断是否还有更多数据
    hasMore.value = newOrders.length === pageSize

    // 如果是下拉刷新，结束下拉刷新状态
    if (isRefresh) {
      uni.stopPullDownRefresh()
    }

    uni.hideLoading()
  } catch (error) {
    console.error('获取订单列表失败:', error)
    uni.showToast({
      title: '获取订单列表失败',
      icon: 'none'
    })

    // 如果是下拉刷新，结束下拉刷新状态
    if (isRefresh) {
      uni.stopPullDownRefresh()
    }

    uni.hideLoading()
  }
}

// 下拉刷新
onPullDownRefresh(() => {
  const type = tabs[activeTab.value].type
  loadOrders(type, true)
})

// 上拉加载更多
onReachBottom(() => {
  if (hasMore.value) {
    currentPage.value++
    const type = tabs[activeTab.value].type
    loadOrders(type)
  }
})

// 订单状态文字映射
const getStatusText = (status) => {
  const statusMap = {
    0: '未支付',
    1: '已支付',
    2: '待发货',
    3: '已发货',
    4: '待自提',
    5: '已完成',
    6: '待退款',
    7: '已取消',
    8: '待评价',
    9: '已退款'
  }
  return statusMap[status] || '未知状态'
}

// 监听标签页切换
watch(activeTab, (newVal) => {
  const type = tabs[newVal].type
  // 切换标签时重置页码和列表
  currentPage.value = 1
  orderList.value = []
  hasMore.value = true
  loadOrders(type)
})

// 页面加载时，根据传入的type参数切换到对应标签
onLoad((options) => {
  if (options.type) {
    const index = tabs.findIndex(tab => tab.type === options.type)
    if (index !== -1) {
      activeTab.value = index
      if (activeTab.value === 0) {
        loadOrders(options.type)
      }
    }
  }
})


// 申请退款
const handleApplyRefund = async (orderId) => {
  try {
    // 弹出输入框让用户输入退款原因
    const res = await new Promise((resolve, reject) => {
      uni.showModal({
        title: '申请退款',
        content: '请输入退款原因',
        editable: true,
        placeholderText: '请输入退款原因',
        confirmColor: '#FF2C54',
        success: (result) => {
          resolve(result)
        },
        fail: (error) => {
          reject(error)
        }
      })
    })
    
    if (res.confirm && res.content) {
      uni.showLoading({ title: '处理中' })
      await applyRefund(orderId, {
        reason: res.content
      })
      uni.hideLoading()
      uni.showToast({
        title: '申请退款成功',
        icon: 'success'
      })
      // 清空订单列表并重新加载
      orderList.value = []
      loadOrders(activeTab.value)
    } else if (res.confirm && !res.content) {
      uni.showToast({
        title: '请输入退款原因',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none'
    })
  }
}



// 确认收货
const handleConfirmReceive = async (orderId) => {
  try {
    // 修改 showModal 的使用方式
    const res = await new Promise((resolve, reject) => {
      uni.showModal({
        title: '提示',
        content: '确定收货吗？',
        confirmColor: '#FF2C54',
        success: (result) => {
          resolve(result)
        },
        fail: (error) => {
          reject(error)
        }
      })
    })
    if (res.confirm) {
      uni.showLoading({ title: '处理中' })
      await completeOrder(orderId)
      uni.hideLoading()
      uni.showToast({
        title: '确认收货成功',
        icon: 'success'
      })
      loadOrders(activeTab.value)
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none'
    })
  }
}

// 确认自提
const confirmPickup = async (orderId) => {
  try {
    // 修改 showModal 的使用方式
    const res = await new Promise((resolve, reject) => {
      uni.showModal({
        title: '提示',
        content: '确定已经自提吗？',
        confirmColor: '#FF2C54',
        success: (result) => {
          resolve(result)
        },
        fail: (error) => {
          reject(error)
        }
      })
    })
    if (res.confirm) {
      uni.showLoading({ title: '处理中' })
      await completeOrder(orderId)
      uni.hideLoading()
      uni.showToast({
        title: '确认自提成功',
        icon: 'success'
      })
      loadOrders(activeTab.value)
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none'
    })
  }
}


// 添加订单操作方法
const handleOrderAction = (action, order) => {
  const actionMessages = {
    cancel: '确认取消订单吗？',
    pay: '确认支付订单吗？',
    complete: '确认完成订单吗？',
    rate: '去评价',
    refundDetail: '退款详情',
    detail: '订单详情'
  }

  if (['cancel', 'pay', 'complete'].includes(action)) {
    uni.showModal({
      title: '提示',
      content: actionMessages[action],
      success: (res) => {
        uni.showToast({
          title: '操作成功',
          icon: 'success'
        })
      }
    })
  } else if (action === 'rate') {
    // 跳转到评价页面
    uni.navigateTo({
      url: `/pages/order/comment?orderId=${order.id}`
    })
  } else if (action === 'refundDetail') {
    // 跳转到退款详情页面
    uni.navigateTo({
      url: `/pages/order/refund-detail?id=${order.id}`
    })
  } else if (action === 'detail') {
    // 跳转到订单详情页面
    uni.navigateTo({
      url: `/pages/order/detail?orderId=${order.id}`
    })
  }
}

// 查看退款详情
const checkRefund = (orderId) => {
  uni.navigateTo({
    url: `/pages/order/refund-detail?id=${orderId}`
  })
}
</script>

<style lang="scss">
// 文本省略的mixin
@mixin text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.order-list-page {
  min-height: 100vh;
  background: #f5f5f5;

  .tab-content {
    padding: 0;
    min-height: 100vh;
  }

  .order-item {
    background: #fff;
    padding: 24rpx 32rpx;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      right: 0;
      top: -10rpx;
      height: 20rpx;
      background: #f5f5f5;
      z-index: 1;
    }

    &:first-child {
      &::before {
        display: none;
      }
    }

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 24rpx;
      border-bottom: 1px solid #f5f5f5;

      .store-info {
        display: flex;
        align-items: center;

        .wd-icon {
          font-size: 32rpx;
          color: #666;
        }

        .store-name {
          font-size: 28rpx;
          color: #666;
          margin-left: 12rpx;
        }
      }

      .order-status {
        color: #ff6010;
        font-size: 28rpx;
        font-weight: 500;
      }
    }

    .goods-list {
      padding: 24rpx 0;

      .goods-item {
        display: flex;
        padding: 4rpx 0;
        align-items: flex-start;

        &+.goods-item {
          margin-top: 20rpx;
        }

        .goods-image {
          width: 160rpx;
          height: 160rpx;
          flex-shrink: 0;
          border-radius: 12rpx;
          margin-right: 24rpx;
          background: #fff;
          border: 1px solid #f5f5f5;
        }

        .goods-info {
          flex: 1;
          min-width: 0;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 160rpx;

          .goods-name {
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
            line-height: 1.4;
            margin-bottom: 8rpx;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            text-overflow: ellipsis;
            word-break: break-all;
          }

          .goods-price {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: auto;

            .price {
              color: #ff6010;
              font-size: 30rpx;
              font-weight: 500;
            }

            .quantity {
              display: flex;
              align-items: center;
              color: #999;
              font-size: 24rpx;

              .multiply {
                margin-right: 4rpx;
              }
            }
          }
        }
      }
    }

    .order-footer {
      padding-top: 24rpx;
      border-top: 1px solid #f5f5f5;

      .total {
        text-align: right;
        font-size: 26rpx;
        color: #666;
        margin-bottom: 20rpx;

        .amount {
          color: #ff6010;
          font-weight: 500;
          font-size: 30rpx;
          margin-left: 12rpx;

          &::before {
            content: '¥';
            font-size: 24rpx;
            margin-right: 2rpx;
          }
        }
      }

      .btn-group {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;
        padding-bottom: 4rpx;

        .wd-button {
          min-width: 160rpx;
          height: 64rpx;
          border-radius: 32rpx;
          font-size: 26rpx;
        }

        .wd-button--primary {
          background: linear-gradient(135deg, #ff6010, #ff7a33);
          border: none;
          box-shadow: 0 4rpx 12rpx rgba(255, 96, 16, 0.2);
        }

        .wd-button--warning {
          color: #666;
          background: #f7f7f7;
          border: none;
        }

        .wd-button--info {
          color: #666;
          background: #f7f7f7;
          border: none;
        }
      }
    }
  }

  .empty-state {
    padding: 160rpx 0;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: calc(100vh - 88rpx); // 减去tabs的高度
    box-sizing: border-box;

    image {
      width: 240rpx;
      height: 240rpx;
      margin-bottom: 24rpx;
      opacity: 0.8;
    }

    text {
      font-size: 28rpx;
      color: #999;
      letter-spacing: 1rpx;
    }
  }

  .load-more {
    text-align: center;
    padding: 30rpx 0;
    display: flex;
    align-items: center;
    justify-content: center;

    .wd-loading {
      margin-right: 10rpx;
    }

    text {
      font-size: 26rpx;
      color: #999;
    }
  }
}
</style>